package com.myrpc.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class BeanUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 通过Bean的名称获得Bean
     * @param beanName Bean的名称
     * @return Bean
     */
    public static Object getBeanByName(String beanName){
        return applicationContext.getBean(beanName);
    }

    /**
     * 通过Bean的类型获得Bean
     * @param beanClass Bean的类型的运行时对象
     * @return Bean
     * @param <T> Bean的类型
     */
    public static <T> T getBeanByType(Class<T> beanClass){
        return applicationContext.getBean(beanClass);
    }
}
